package com.example.radio_button

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.annotation.RequiresApi
import java.util.*

class MainActivity : AppCompatActivity() {
    //    延迟初始化
    private lateinit var radioGroup: RadioGroup

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

//        获取选中的状态
        radioGroup = findViewById<RadioGroup>(R.id.radio_group_1)
        radioGroup.setOnCheckedChangeListener { _: RadioGroup, checkId: Int ->
            //            获取选中的状态
            val selectRadioButton = findViewById<RadioButton>(checkId)
            Toast.makeText(this, "选中了" + selectRadioButton.text + "按钮", Toast.LENGTH_SHORT).show()
        }
    }

    public fun summit(view: View?): Unit {
        for (i in 0..radioGroup.childCount) {
            val child = radioGroup.getChildAt(i)
            //进行判别之后，编译器可以自动进行强制转换
            if (child is RadioButton && child.isChecked) {
                Toast.makeText(this, "提交了性别：" + child.text, Toast.LENGTH_SHORT).show()
            }
        }
    }
}
